import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {equalValidator, phoneValidator} from '../../../valitor/Validators';
import {User, UserService} from '../../../services/user/user.service';
import {routerNgProbeToken} from '@angular/router/src/router_module';
import {Router} from '@angular/router';
import {StringUtils} from '../../../directives/function/StringUtils';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  message: string;

  stautuCode: boolean;

  formModel: FormGroup;

  constructor(fb: FormBuilder, private userService: UserService, private router: Router) {
    this.formModel = fb.group({
      username: ['', [Validators.required, Validators.maxLength(122)]],
      passwords: fb.group({
        password: ['', Validators.minLength(6)],
        confirm: ['']
      }, {validator: equalValidator}),
      phoneNumber: ['', phoneValidator],
      address: ['', Validators.required]
    });
  }

  ngOnInit() {
  }

  onRegister() {
    if (this.formModel.valid) {
      this.userService.registerUser(this.getUser()).subscribe((data) => {
       this.stautuCode = StringUtils.checkStatus(data);
      });
      setTimeout(() => {
        if (this.stautuCode) {
          this.userService.message = '注册成功，请登录';
          return this.router.navigateByUrl('/login');
        } else {
          this.message = '注册失败，请联系管理员!';
          return this.router.navigateByUrl('/register');
        }
      }, 1000);

    }
  }

  getUser(): User {
    let username: string = this.formModel.get('username').value;
    let password: string = this.formModel.get(['passwords', 'password']).value;
    let phoneNumber: number = this.formModel.get('phoneNumber').value;
    let address: string = this.formModel.get('address').value;
    let user: User = new User(username, password, phoneNumber, address);
    console.log(user);
    return user;
  }
}
